//
//  SubscribeClassifyViewController.m
//  suRead
//
//  Created by lidi on 2018/11/29.
//  Copyright © 2018 bao. All rights reserved.
//

#import "SubscribeClassifyViewController.h"
#import "Masonry.h"
#import "UIViewController+HUD.h"
#import "UIControl+Blocks.h"
#import "MJRefresh.h"
#import "ServiceSubscribe.h"
#import "UIViewController+EmptyDataSet.h"
#import "SubscribeListViewController.h"

@interface SubscribeClassifyViewController ()<UIScrollViewDelegate,UIGestureRecognizerDelegate>
@property (nonatomic,strong) UIScrollView *headerScrollView;
@property (nonatomic,strong) UIScrollView *contentScrollView;
@property (nonatomic,strong) UIView *contentScrollViewContentView;

@property (nonatomic,assign) NSInteger selectedIndex;
@property (nonatomic,strong) NSMutableArray *tagsArray;

@property (nonatomic,strong) NSArray *tags;

@property (nonatomic,strong) NSMutableDictionary *viewControllersHandle;
@property (nonatomic,strong) NSMutableArray *visiableViewControllers;
@end

@implementation SubscribeClassifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // enable slide-back
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tagsArray = [NSMutableArray array];
    self.selectedIndex = -1;
    self.viewControllersHandle = [NSMutableDictionary dictionary];
    self.visiableViewControllers = [NSMutableArray array];
    [self loadClassify];
}

///加载分类
- (void)loadClassify {
    [self emptyDataSetClearAllNotice];
    
    __weak typeof(self) weak_self = self;
    [ServiceSubscribe doFetchClassify:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
         weak_self.tags = responseObject;
         [self initViews];
    }
    failure:^(NSString *message)
     {
         //重连界面
         [weak_self emptyDataSetShowNetWorkAvaliable:^{
             [weak_self loadClassify];
         }];
     }];
}

/**
 *  头部导航栏 新闻内容页
 */
- (void)initViews
{
    __weak typeof(self) weak_self = self;
    
    //头部导航栏
    UIView *navigationBarView = [UIView new];
    navigationBarView.backgroundColor = [[UIColor alloc] initWithRed:190.0f / 255.0f green:30.0f / 255.0f blue:30.0f / 255.0f alpha:1];
    [self.view addSubview:navigationBarView];
    [navigationBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(navigationBarView.superview);
        if (iPhoneX) {
            make.height.equalTo(@88.0f);
        } else {
            make.height.equalTo(@64.0f);
        }
    }];
    
    UIView *titleViewContainer = [UIView new];
    [navigationBarView addSubview:titleViewContainer];
    [titleViewContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(titleViewContainer.superview);
        make.height.equalTo(@44.0f);
    }];
    
    //标题
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = @"添加订阅";
    titleLabel.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:17.0f];
    titleLabel.textColor = [UIColor whiteColor];
    [titleViewContainer addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(titleLabel.superview);
    }];
    
    //返回
    UIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonBack.tintColor = [UIColor whiteColor];
    [buttonBack setImage:[[UIImage imageNamed:@"button_backward"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    [titleViewContainer addSubview:buttonBack];
    [buttonBack addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        [weak_self.navigationController popViewControllerAnimated:YES];
    }];
    [buttonBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(buttonBack.superview).offset(15.0);
        make.top.bottom.equalTo(buttonBack.superview);
        make.width.equalTo(@44.0f);
    }];
    
    //标签选择栏
    UIView *tagContainerView = [UIView new];
    [self.view addSubview:tagContainerView];
    [tagContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(navigationBarView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.height.equalTo(@35.0f);
    }];
    
    self.headerScrollView = [UIScrollView new];
    self.headerScrollView.showsHorizontalScrollIndicator = NO;
    [tagContainerView addSubview:self.headerScrollView];
    [self.headerScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(tagContainerView);
        make.top.bottom.equalTo(tagContainerView);
    }];
    
    //底部横线
    UIView *bottomLine = [UIView new];
    bottomLine.backgroundColor = [UIColor lightGrayColor];
    [tagContainerView addSubview:bottomLine];
    [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(bottomLine.superview);
        make.height.equalTo(@.5f);
    }];
    
    //内容
    self.contentScrollView = [UIScrollView new];
    self.contentScrollView.pagingEnabled = YES;
    self.contentScrollView.delegate = self;
    [self.view addSubview:self.contentScrollView];
    [self.contentScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(tagContainerView.mas_bottom);
        make.left.right.bottom.equalTo(weak_self.view);
    }];
    
    [self refreshTags:self.tags];
}

//MARK:-刷新界面
- (void)refreshTags:(NSArray *) tags_ {
    
    for (UIView *sub in self.contentScrollView.subviews) {
        [sub removeFromSuperview];
    }
    for (UIView *sub in self.headerScrollView.subviews) {
        [sub removeFromSuperview];
    }
    
    [self.contentScrollView setContentOffset:CGPointZero];
    [self.headerScrollView setContentOffset:CGPointZero];
    
    _selectedIndex = -1;
    self.tags = tags_;
    self.tagsArray = [NSMutableArray array];
    self.viewControllersHandle = [NSMutableDictionary dictionary];
    self.visiableViewControllers = [NSMutableArray array];
    
    UIView *headerScrollViewContentView = [UIView new];
    [self.headerScrollView addSubview:headerScrollViewContentView];
    
    self.contentScrollViewContentView = [UIView new];
    [self.contentScrollView addSubview:self.contentScrollViewContentView];
    [self.contentScrollViewContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.contentScrollViewContentView.superview);
        make.height.mas_equalTo(self.contentScrollView.mas_height);
        make.width.mas_equalTo(@([UIScreen mainScreen].bounds.size.width * [self.tags count]));
    }];
    
    UIView *headerPreView = nil;
    
    CGFloat headWidth = 0;
    CGFloat distance = 15.0f;
    
    for (NSInteger i=0; i<[self.tags count]; i++) {
        NSString *title = [[self.tags objectAtIndex:i] objectForKey:@"classify_name"];
        //添加导航
        UILabel *labelTitle = [UILabel new];
        labelTitle.backgroundColor = [UIColor clearColor];
        labelTitle.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:16.0f];
        labelTitle.textAlignment = NSTextAlignmentCenter;
        labelTitle.text = title;
        labelTitle.tag = i;
        
        CGSize sizeString = [title sizeWithAttributes:@{NSFontAttributeName:labelTitle.font}];
        CGFloat sizeWidth = sizeString.width + distance;
        headWidth += sizeWidth;
        
        [headerScrollViewContentView addSubview:labelTitle];
        [labelTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            if (!headerPreView) {
                make.left.equalTo(labelTitle.superview);
            }
            else {
                make.left.mas_equalTo(headerPreView.mas_right);
            }
            
            make.top.bottom.equalTo(labelTitle.superview);
            make.width.equalTo( @(sizeWidth) );
            
        }];
        headerPreView = labelTitle;
        
        UITapGestureRecognizer *tagTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tagTap:)];
        [labelTitle addGestureRecognizer:tagTap];
        labelTitle.userInteractionEnabled = YES;
        [self.tagsArray addObject:labelTitle];
    }
    
    [headerScrollViewContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.headerScrollView).insets(UIEdgeInsetsZero);
        make.height.mas_equalTo(self.headerScrollView.mas_height);
        make.width.equalTo(@(headWidth));
    }];
    
    //初始选择第一项
    self.selectedIndex = 0;
    [self contentScrollToPage:0];
}

//标签点击
- (void)tagTap:(UITapGestureRecognizer *)ges
{
    NSInteger index = ges.view.tag;
    self.selectedIndex = index;
    [self contentScrollToPage:index];
    self.contentScrollView.contentOffset = CGPointMake([UIScreen mainScreen].bounds.size.width * index, 0);
}

- (void)setSelectedIndex:(NSInteger)selectedIndex
{
    __weak typeof(self) weak_self = self;
    
    if (selectedIndex>=0 && self.selectedIndex != selectedIndex) {
        UILabel *labelTitle = [self.tagsArray objectAtIndex:selectedIndex];
        
        //判断标签右边是否完全显示
        if (labelTitle.frame.origin.x +labelTitle.frame.size.width - self.headerScrollView.contentOffset.x > self.headerScrollView.frame.size.width) {
            CGFloat x = self.headerScrollView.contentOffset.x - (self.headerScrollView.contentOffset.x - labelTitle.frame.origin.x + self.headerScrollView.frame.size.width - labelTitle.frame.size.width);
            [self.headerScrollView setContentOffset:CGPointMake(x, 0) animated:YES];
        }
        
        //判断标签右边是否完全显示
        if (labelTitle.frame.origin.x < self.headerScrollView.contentOffset.x) {
            CGFloat x = labelTitle.frame.origin.x;
            [self.headerScrollView setContentOffset:CGPointMake(x, 0) animated:YES];
        }
        
        NSInteger preIndex = self.selectedIndex;
        
        if (preIndex >=0) {
            UILabel *labelPre = [weak_self.tagsArray objectAtIndex:preIndex];
            labelPre.textColor = [UIColor blackColor];
        }
        
        labelTitle.textColor = [[UIColor alloc] initWithRed:190.0f / 255.0f green:30.0f / 255.0f blue:30.0f / 255.0f alpha:1];
        [UIView animateWithDuration:.1f animations:^{
            [labelTitle.superview layoutIfNeeded];
        } completion:^(BOOL finished) {
            
        }];
    }
    
    _selectedIndex = selectedIndex;
}

//内容滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!scrollView.isDragging) {
        return;
    }
    
    if (scrollView == self.contentScrollView) {
        // 得到每页宽度
        CGFloat pageWidth = [UIScreen mainScreen].bounds.size.width;
        // 根据当前的x坐标和页宽度计算出当前页数
        NSInteger currentPage = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
        
        if (currentPage != self.selectedIndex) {
            self.selectedIndex = currentPage;
            [self contentScrollToPage:currentPage];
        }
    }
}

- (void)contentScrollToPage:(NSInteger)pageIndex_
{
    [self addContentAtIndex:pageIndex_];
    
    //找出左边一个加上
    NSInteger preIndex = pageIndex_ - 1;
    if (preIndex >= 0) {
        [self addContentAtIndex:preIndex];
    }
    //找出右边一个加上
    NSInteger nextIndex = pageIndex_ + 1;
    if (nextIndex < [self.tags count]) {
        [self addContentAtIndex:nextIndex];
    }
    
    NSMutableArray *readyToMove = [NSMutableArray array];
    //其他的删掉
    for (SubscribeListViewController *controller in self.visiableViewControllers) {
        if (controller.view.tag != pageIndex_ && controller.view.tag != preIndex && controller.view.tag != nextIndex) {
            [controller removeFromParentViewController];
            [controller.view removeFromSuperview];
            [readyToMove addObject:controller];
        }
    }
    
    for (SubscribeListViewController *controller in readyToMove) {
        [self.visiableViewControllers removeObject:controller];
    }
    
}

- (void)addContentAtIndex:(NSInteger)index_
{
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    //先把当前view加上
    SubscribeListViewController *currentViewController = [self.viewControllersHandle objectForKey:@(index_)];
    if (!currentViewController) {
        currentViewController = [SubscribeListViewController new];
        currentViewController.view.tag = index_;
        NSDictionary *tag = self.tags[index_];
        currentViewController.pid = [[tag objectForKey:@"id"] integerValue];
        [self.viewControllersHandle setObject:currentViewController forKey:@(index_)];
    }
    
    if (![self.visiableViewControllers containsObject:currentViewController]) {
        //加上
        [self addChildViewController:currentViewController];
        [currentViewController didMoveToParentViewController:self];
        [self.contentScrollViewContentView addSubview:currentViewController.view];
        [currentViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(currentViewController.view.superview).offset(index_ * screenWidth);
            make.top.bottom.equalTo(currentViewController.view.superview);
            make.width.equalTo(@(screenWidth));
        }];
        
        [self.visiableViewControllers addObject:currentViewController];
    }
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return YES;
}

@end
